﻿@page "/admin/listtimedtasks"
@attribute [Authorize(Roles = "Admin")]

@inject IHttpService _httpService
@inject IPopupService PopupService
@inject NavigationManager NavigationManager

<CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip Title="定时任务版块" />

<MDCard>
    <DataTableCard TModel="TimedTaskOverviewModel" Headers="_headers" ApiUrl="@(_baseUrl)" Title="@($"{_name}列表")" OnClickAdd="AddItem" @ref="dataTableCard">
        <ItemColContent>
            @if (context.Header.Value == "actions")
            {
                <div style="width: 140px;">
                    <MIcon Color="success"
                           Class="mr-2"
                           OnClick="()=>EditItem(context.Item)">@IconType.Edit.ToIconString()</MIcon>
                    <MIcon Color="info"
                           Class="mr-2"
                           OnClick="()=>RunItem(context.Item)">@IconType.Runing.ToIconString()</MIcon>
                    @if (context.Item.IsPause)
                    {
                        <MIcon Color="success"
                               Class="mr-2"
                               OnClick="()=>PauseItem(context.Item,false)">@IconType.Run.ToIconString()</MIcon>
                    }
                    else
                    {
                        <MIcon Color="error"
                               Class="mr-2"
                               OnClick="()=>PauseItem(context.Item,true)">@IconType.Stop.ToIconString()</MIcon>
                    }
                </div>
            }
            else if (context.Header.Value == nameof(TimedTaskOverviewModel.IsLastFail))
            {
                <CnGalWebSite.Shared.MasaComponent.PC.Admin.TimedTasks.StateChip IsLastFail="context.Item.IsLastFail" IsPause="context.Item.IsPause" IsRuning="context.Item.IsRuning" />
            }
            else if (context.Header.Value == nameof(TimedTaskOverviewModel.ExecuteType))
            {
                <CnGalWebSite.Shared.MasaComponent.PC.Admin.TimedTasks.ExecuteTypeChip Type="context.Item.ExecuteType" />
            }
            else if (context.Header.Value == nameof(TimedTaskOverviewModel.Type))
            {
                @context.Item.Type.GetDisplayName()
            }
            else if (context.Header.Value == nameof(TimedTaskOverviewModel.IntervalTime))
            {
                if (context.Item.ExecuteType == TimedTaskExecuteType.EveryDay)
                {
                    @context.Item.EveryTime?.ToString("HH:mm:ss")
                }
                else
                {
                    @($"{context.Item.IntervalTime / 60.0:0.0} 小时")
                }

            }
            else if (context.Header.Value == nameof(TimedTaskOverviewModel.LastExecutedTime))
            {

                @context.Item.LastExecutedTime?.ToString("yyyy-MM-dd HH:mm")

            }
            else
            {
                @context.Value
            }
        </ItemColContent>
    </DataTableCard>

</MDCard>

<MDialog @bind-Value="_editDialog"
         MaxWidth="1200">
    <CnGalWebSite.Shared.MasaComponent.PC.Admin.TimedTasks.EditCard Id="_editedItemId" OnEdited="OnEdited" @ref="editCard" />
</MDialog>
@code {
    private string _baseUrl =ToolHelper.TaskApiPath+ "api/timedtasks/List";
    private string _name = "定时任务";

    private List<DataTableHeader<TimedTaskOverviewModel>> _headers = new List<DataTableHeader<TimedTaskOverviewModel>>
{
          new ()
          {
            Text= "Id",
            Align= DataTableHeaderAlign.Start,
            Value= nameof(TimedTaskOverviewModel.Id)
          },
          new (){ Text= "名称", Value= nameof(TimedTaskOverviewModel.Type)},
          new (){ Text= "参数", Value= nameof(TimedTaskOverviewModel.Parameter)},
          new (){ Text= "类型", Value= nameof(TimedTaskOverviewModel.ExecuteType)},
          new (){ Text= "时间", Value= nameof(TimedTaskOverviewModel.IntervalTime)},
          new (){ Text= "上次执行时间", Value= nameof(TimedTaskOverviewModel.LastExecutedTime)},
          new (){ Text= "状态", Value= nameof(TimedTaskOverviewModel.IsLastFail)},
          new (){ Text= "操作", Value= "actions",Sortable=false }
    };

    DataTableCard<TimedTaskOverviewModel> dataTableCard;

    CnGalWebSite.Shared.MasaComponent.PC.Admin.TimedTasks.EditCard editCard;
    private bool _editDialog;
    private int _editedItemId;
    private bool _detailDialog;


    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    public async void EditItem(TimedTaskOverviewModel item)
    {
        _editedItemId = item.Id;
        _editDialog = true;
        StateHasChanged();
        if (editCard != null)
        {
            await editCard.Refresh();
        }
    }

    public void OnEdited()
    {
        _editDialog = false;
        StateHasChanged();
        if (dataTableCard != null)
        {
            dataTableCard.GetDataFromApi();
        }
    }

    public async Task AddItem()
    {
        _editedItemId = 0;
        _editDialog = true;
        StateHasChanged();
        if (editCard != null)
        {
            await editCard.Refresh();
        }
    }

    public async Task PauseItem(TimedTaskOverviewModel model, bool isPause)
    {
        string operationName = (isPause ? "暂停" : "启动") + _name;
        try
        {
            var obj = await _httpService.PostAsync<PauseTimedTaskModel, CnGalWebSite.Core.Models.Result>(ToolHelper.TaskApiPath + "api/timedtasks/PauseTimedTask", new PauseTimedTaskModel { Ids = new int[] { model.Id }, IsPause = isPause });

            if (obj.Success == false)
            {
                await PopupService.ToastAsync(operationName + "失败",  AlertTypes.Error);
            }
            else
            {

                await PopupService.ToastAsync(operationName + "成功", AlertTypes.Success);
                dataTableCard.GetDataFromApi();

            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, operationName + "失败");
        }
    }

    public async Task RunItem(TimedTaskOverviewModel model)
    {
        string operationName = "运行"+_name;
        try
        {
            var task = _httpService.PostAsync<RunTimedTaskModel, CnGalWebSite.Core.Models.Result>(ToolHelper.TaskApiPath + "api/timedtasks/RunTimedTask", new RunTimedTaskModel { Ids = new int[] { model.Id } });
            dataTableCard.GetDataFromApi();
            await PopupService.ToastAsync("正在运行任务", AlertTypes.Info);
            var obj = await task;

            if (obj.Success == false)
            {
                await PopupService.ToastAsync(operationName + "失败",  AlertTypes.Error);
            }
            else
            {

                await PopupService.ToastAsync(operationName + "成功", AlertTypes.Success);
                dataTableCard.GetDataFromApi();

            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, operationName + "失败");
        }
    }
}
